<template>
  <el-drawer v-model="visible" class="add-special jzt-drawer">
    <template #title>
      <div class="title-box">
        <CustomTitle title="自定义特殊条件定价" />(系数定义：1为保持现有成本价，不加价不减价，以此推算，成本价*系数=售价)
      </div>
    </template>
    <div class="content">
      <div class="sift">
        <div class="title">通用筛选</div>
        <el-scrollbar height="calc(100vh - 185px)" class="select-list">
          <el-form label-position="top">
            <div class="date-range">
              <el-form-item label="上架日期">
                <el-date-picker
                  v-model="forms.listingStartTime"
                  value-format="YYYY-MM-DD"
                  :teleported="false"
                  clearable
                  :disabled="edit"
                />
              </el-form-item>
              <el-form-item>
                <div class="end">
                  至
                  <el-date-picker
                    v-model="forms.listingEndTime"
                    value-format="YYYY-MM-DD"
                    :teleported="false"
                    clearable
                    :disabled="edit"
                  />
                </div>
              </el-form-item>
            </div>
            <el-form-item v-for="(item, index) in siftList" :label="item.stastsName" :prop="item.stastsId">
              <div class="checkbox-list">
                <template v-for="(option, index) in item.children">
                  <div
                    v-if="!option.children"
                    :class="isChecked(item, option) ? 'active item' : 'item'"
                    @click="checked(item, option)"
                  >
                    {{ option.stastsName }}
                    <img src="@/assets/images/active.png" alt="" />
                  </div>
                  <div v-else class="select-box">
                    {{ option.stastsName }}
                    <el-select
                      style="width: 130px"
                      v-model="selectValue[option.stastsId]"
                      :multiple-limit="option.stasType == 3 ? 0 : 1"
                      clearable
                      @remove-tag="delSelect(item, option, index)"
                      @clear="clearSelect(item, option)"
                      :disabled="edit"
                    >
                      <el-option
                        v-for="i in option.children"
                        :value="i.stastsId"
                        :label="i.stastsName"
                        @click="selectChange(item, option, i, option.stasType != 3)"
                      >
                      </el-option>
                    </el-select>
                  </div>
                </template>
              </div>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <el-scrollbar max-height="calc(100vh - 125px)">
        <template v-if="!forms.pricingList.length">
          <el-empty />
          <div class="add-button">
            <el-button type="primary" @click="add" v-if="!edit">添加区间</el-button>
          </div>
        </template>
        <div class="range-list">
          <div v-for="(item, index) in forms.pricingList">
            <div class="item">
              <el-form :model="item" ref="itemRef" :rules="rules">
                <div class="head">
                  <div class="price-range">
                    <el-form-item label="成本价范围：" prop="startPrice">
                      <el-input
                        v-model="item.startPrice"
                        @keyup.enter="inquire(item, index)"
                        @blur="inquire(item, index)"
                        :disabled="edit"
                      ></el-input>
                    </el-form-item>
                    <el-form-item prop="endPrice">
                      <div class="end">
                        至<el-input
                          v-model="item.endPrice"
                          @keyup.enter="inquire(item, index)"
                          @blur="inquire(item, index)"
                          :disabled="edit"
                        ></el-input>
                      </div>
                    </el-form-item>
                  </div>
                  <div class="select-input">
                    <el-form-item label="设置为：" prop="coefficientType">
                      <el-select
                        style="width: 130px; height: 30px; overflow: hidden"
                        v-model="item.coefficientType"
                        :disabled="edit"
                      >
                        <el-option :value="1" label="正价系数"></el-option>
                        <el-option :value="2" label="特价系数"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item prop="pricingCoefficient">
                      <el-input
                        v-model="item.pricingCoefficient"
                        @keyup.enter="inquire(item, index)"
                        @blur="inquire(item, index)"
                        :disabled="edit"
                      >
                      </el-input>
                    </el-form-item>
                  </div>
                </div>
              </el-form>
              <div class="info">
                <div class="info-item">
                  <div v-if="!isShow.includes(item.productNum)">{{ item.productNum }}</div>
                  <div v-else>--</div>
                  <div>被调价商品{{ item.productNum }}</div>
                </div>
                <div class="info-item">
                  <div v-if="!isShow.includes(item.orderNum)">{{ item.orderNum }}</div>
                  <div v-else>--</div>
                  <div>历史订单数</div>
                </div>
                <div>
                  <div class="info-item">
                    <div>
                      <div v-if="!isShow.includes(item.averageGrossMargin)">
                        {{ item.averageGrossMargin }}%
                        <img
                          v-if="Number(item.averageGrossMargin)"
                          :src="Number(item.averageGrossMargin) > 0 ? up : down"
                          alt=""
                        />
                      </div>
                      <div v-else>--</div>
                    </div>
                    <div>平均毛利润</div>
                  </div>
                  <div class="info-item">
                    <div v-if="!isShow.includes(item.oldAverageGrossMargin)">
                      {{ item.oldAverageGrossMargin + "%" }}
                    </div>
                    <div v-else>--</div>
                    <div>原有毛利润值</div>
                  </div>
                </div>
                <div class="info-item">
                  <div v-if="!isShow.includes(item.revenueGrowthAmount)">≈{{ item.revenueGrowthAmount }}</div>
                  <div v-else>--</div>
                  <div>
                    收益增长金额（<span
                      :class="Number(item.revenueGrowthAmount) - Number(item.oldRevenueGrowthAmount) < 0 ? 'red' : 'green'"
                    >
                      {{
                        !isNaN(Number(item.revenueGrowthAmount) - Number(item.oldRevenueGrowthAmount))
                          ? Number(item.revenueGrowthAmount) - Number(item.oldRevenueGrowthAmount)
                          : 0
                      }}</span
                    >）
                  </div>
                </div>
              </div>
            </div>
            <img @click="forms.pricingList.splice(index, 1)" v-if="!edit" src="@/assets/images/del.png" alt="" />
          </div>
          <div class="add" v-if="forms.pricingList.length && !edit" @click="add">
            <el-icon> <CirclePlusFilled /> </el-icon>继续添加区间
          </div>
        </div>
      </el-scrollbar>
    </div>
    <template #footer>
      <div class="footer-btn">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="save" v-if="!edit">保存为定价草稿</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import CustomTitle from "@/components/CustomTitle/index.vue";
import up from "@/assets/images/up.png";
import down from "@/assets/images/down.png";
import { ref, computed, onMounted } from "vue";
import { getFilterAttr, getSpecialGrossMargin } from "@/apis/pricing";

const isShow = [null, undefined];
const props = defineProps({
  show: {
    type: Boolean,
    required: true,
    default: false
  },
  data: {
    type: Object,
    required: true,
    default: () => {
      return {};
    }
  },
  categoryId: {
    type: String,
    required: true
  },
  edit: {
    type: Boolean,
    default: true
  }
});
const selectValue = ref({});
const forms = ref({
  pricingList: [],
  conditionList: [],
  pricingType: 1
});
const itemRef = ref(null);
const siftList = ref([]);
const defaultItem = {};
const rules = {
  pricingCoefficient: [
    { required: true, message: "请输入系数", trigger: "blur" },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的系数", trigger: "blur" }
  ],
  startPrice: [
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
    { required: true, message: "请输入", trigger: "blur" }
  ],
  endPrice: [
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
    { required: true, message: "请输入", trigger: "blur" }
  ],
  coefficientType: [{ required: true, message: "请选择", trigger: "change" }]
};
/**
 * 选中
 */
const checked = (item, option) => {
  if (props.edit) return;
  if (!forms.value.conditionList.some(v => v.stastsId == item.stastsId)) {
    forms.value.conditionList.push({
      stastsId: item.stastsId,
      stastsName: item.stastsName,
      stastsVal: [option.stastsName],
      stastsValId: [option.stastsId],
      stasType: item.stasType,
      isCommon: item.isCommon
    });
  } else {
    for (let v of forms.value.conditionList) {
      if (v.stastsId == item.stastsId) {
        if (v.stastsValId.some(val => val == option.stastsId)) {
          v.stastsValId = v.stastsValId.filter(val => val != option.stastsId);
        } else {
          if (option.stasType == 3) {
            v.stastsVal.push(item.stastsName);
            v.stastsValId.push(item.stastsId);
          } else {
            v.stastsVal = [option.stastsName];
            v.stastsValId = [option.stastsId];
          }
        }
      }
    }
  }
};
/**
 * 是否选中
 */
const isChecked = (item, option) => {
  for (let v of forms.value.conditionList) {
    if (v.stastsId == item.stastsId) {
      return v.stastsValId.some(val => val == option.stastsId);
    }
  }
};
/**
 * 添加区间
 */
const add = () => {
  forms.value.pricingList.push({ ...defaultItem });
};
const emit = defineEmits(["update:show", "comfirm"]);
const visible = computed({
  set: val => {
    emit("update:show", val);
  },
  get: () => {
    return props.show;
  }
});
/**
 * 保存
 */
const save = async () => {
  const formsData = JSON.parse(JSON.stringify(forms.value));
  if (forms.value.listingStartTime) {
    if (forms.value.listingStartTime.indexOf(" 00:00:00") == -1) {
      formsData.listingStartTime = forms.value.listingStartTime + " 00:00:00";
    }
  }
  if (forms.value.listingEndTime) {
    if (forms.value.listingEndTime.indexOf(" 23:59:59") == -1) {
      formsData.listingEndTime = forms.value.listingEndTime + " 23:59:59";
    }
  }
  formsData.conditionList = formsData.conditionList.map(v => {
    return {
      ...v,
      stastsVal: v.stastsVal.join(","),
      stastsValId: v.stastsValId.join(",")
    };
  });
  if (forms.value.pricingList?.length) {
    let arr = [];
    itemRef.value.forEach(v => {
      arr.push(
        new Promise(resolve => {
          v.validate(valid => {
            resolve(valid);
          });
        })
      );
    });
    const result = await Promise.all(arr);
    if (result.every(v => v)) emit("comfirm", formsData);
  } else {
    emit("comfirm", formsData);
  }
};
/**
 * 获取筛选条件
 */
const getAtrr = async () => {
  const res = await getFilterAttr({ categoryId: props.categoryId });
  siftList.value = res.data;
  forms.value.conditionList
    .map(v => v.stastsValId.join(","))
    .flat(2)
    .forEach(v => {
      selectValue.value[getParent(v)] = v;
    });
};
/**
 * 选择三级框
 */
const selectChange = (item, option, i, isDel) => {
  if (isDel) {
    for (let v of forms.value.conditionList) {
      if (v.stastsId == item.stastsId) {
        v.stastsValId = v.stastsValId.filter(val => val != option.stastsId);
      }
    }
    for (let v of item.children) {
      if (v.stastsId != option.stastsId) {
        delete selectValue.value[v.stastsId];
      }
    }
  }
  checked(item, i);
};
/**
 * 清空选择框
 */
const clearSelect = (item, option) => {
  for (let v of forms.value.conditionList) {
    if (v.stastsId == item.stastsId) {
      v.stastsValId = v.stastsValId.filter(val => val != option.stastsId);
      v.stastsVal = v.stastsVal.filter(val => val != option.stastsName);
    }
  }
};
/**
 * 查询毛利润
 */
const inquire = async (item, index) => {
  const redg = /^[0-9]+(\.[0-9]{1,2})?$/;
  const arr = [redg.test(item.startPrice), redg.test(item.endPrice), redg.test(item.pricingCoefficient)];
  if (arr.every(v => v)) {
    const res = await getSpecialGrossMargin({
      ...item,
      categoryId: props.categoryId,
      listingStartTime: forms.value.listingStartTime ? forms.value.listingStartTime + " 00:00:00" : undefined,
      listingEndTime: forms.value.listingEndTime ? forms.value.listingEndTime + " 23:59:59" : undefined,
      stastsValIds: forms.value.conditionList.map(v => v.stastsValId).flat(2)
    });
    forms.value.pricingList[index] = { ...item, ...res.data };
  }
};
/**
 * 获取父级
 */
const getParent = id => {
  let arr = [];
  const traverse = tree => {
    for (const v of tree) {
      if (v.stastsId == id) {
        arr.unshift(v);
        return v;
      } else if (v.children && v.children.length) {
        if (traverse(v.children)) {
          arr.unshift(v);
          return v;
        }
      }
    }
    return null;
  };
  traverse(siftList.value);
  return arr[arr.length - 2].stastsId;
};
/**
 * 回显
 */
const echo = () => {
  if (Object.keys(props.data).length) {
    forms.value.pricingList = JSON.parse(JSON.stringify(props.data.pricingList));
    forms.value.conditionList = props.data.conditionList.map(v => {
      const stastsValId = v.stastsValId ? v.stastsValId.split(",") : [];
      const stastsVal = v.stastsVal ? v.stastsVal.split(",") : [];
      return {
        ...v,
        stastsVal,
        stastsValId
      };
    });
    forms.value.pricingType = props.data.pricingType;
    forms.value.listingStartTime = props.data.listingStartTime;
    forms.value.listingEndTime = props.data.listingEndTime;
    forms.value.assemblyId = props.data.assemblyId;
  }
};
onMounted(() => {
  getAtrr();
  echo();
});
</script>

<style lang="scss" scoped>
$border: 1px solid #e2e8f0;
$topic: #007dff;

.footer-btn {
  padding: 0 20px;
  height: 60px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: end;
}
.title-box {
  display: flex;
  align-items: center;
  gap: 4px;
}
.content {
  display: flex;

  .sift {
    width: 30vw;
    height: calc(100vh - 125px);
    border-right: $border;
    box-sizing: border-box;
    background: white;

    .title {
      color: #3d3d3d;
      padding: 20px;
    }

    .date-range {
      display: flex;
      gap: 10px;

      .end {
        padding-top: 30px;
        display: flex;
        align-items: center;
        gap: 10px;
      }

      ::v-deep(.el-input) {
        width: unset;
      }
    }

    ::v-deep(.el-form-item__label) {
      color: #86909c;
    }

    .select-list {
      padding: 0 20px;
    }

    .checkbox-list {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;

      > .item {
        height: 26px;
        box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.16);
        border-radius: 4px;
        border: 1px solid transparent;
        line-height: 26px;
        padding: 0 16px;
        cursor: pointer;
        flex: 1;
        white-space: nowrap;

        > img {
          display: none;
        }
      }

      .select-box {
        display: flex;
        white-space: nowrap;
        gap: 10px;
      }

      .active {
        border: 1px solid $topic;
        position: relative;
        overflow: hidden;

        > img {
          display: block;
          width: 19px;
          height: 18px;
          position: absolute;
          right: -1px;
          bottom: -1px;
        }
      }
    }

    .date-range {
      display: flex;
      align-items: center;
    }
  }

  .add-button {
    display: flex;
    justify-content: center;
  }

  .range-list {
    padding: 20px;
    width: 60vw;
    box-sizing: border-box;

    > div {
      display: flex;
      align-items: center;
      gap: 20px;

      img {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }

    .item {
      background: #f6f8fa;
      border-radius: 10px;
      margin-bottom: 20px;
      flex: 1;

      ::v-deep(.el-input__prefix .el-select) {
        border-right: $border;
      }

      .head {
        display: flex;
        gap: 20px;
        padding: 20px 20px 0;
        border-bottom: $border;
        align-items: center;

        ::v-deep(.el-input__wrapper),
        ::v-deep(.el-select__wrapper) {
          background: white;
          border: none;
        }

        .price-range {
          display: flex;
          gap: 10px;
          align-items: center;

          .end {
            display: flex;
            align-items: center;
            gap: 10px;
          }

          ::v-deep(.el-input) {
            width: unset;
          }
        }

        .select-input {
          display: flex;

          ::v-deep(.el-form-item) {
            &::last-child {
              flex: 1;
            }
          }
        }
      }

      .info {
        display: grid;
        grid-template-columns: repeat(2, 1fr) 2fr 1fr;
        padding: 20px;
        box-sizing: border-box;
        gap: 10px;

        > div {
          border-radius: 10px;
          border: 1px solid #e1e6ed;
          height: 80px;
          background: rgba(225, 230, 237, 0.5);
          border: 1px solid #e1e6ed;
        }

        > div:nth-child(3) {
          display: flex;

          > div {
            width: 50%;

            img {
              width: 16px;
              height: 16px;
            }
          }

          > div:first-child {
            border-right: 1px solid white;
          }
        }

        .info-item {
          > div {
            height: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          > div:first-child {
            font-size: 18px;
          }

          > div:last-child {
            font-size: 14px;
            color: #86909c;
          }

          .red {
            color: #ff0000;
          }

          .green {
            color: #19cc15;
          }
        }
      }
    }

    .add {
      color: $topic;
      display: flex;
      height: 40px;
      gap: 10px;
      align-items: top;
      user-select: none;
      width: 120px;
    }
  }
}
</style>
<style lang="scss">
$border: 1px solid #e2e8f0;

.add-special {
  border-radius: 10px 0 0 10px;
  width: 90vw !important;

  .el-drawer__footer {
    box-shadow: 0px -3px 10px 0px rgba(143, 162, 185, 0.1);
    align-items: center;
    padding: 0 !important;
  }

  .el-drawer__header {
    margin-bottom: 0 !important;
    border-bottom: $border;
    padding-bottom: 20px !important;
  }

  .el-drawer__body {
    padding: 0 !important;
  }
}

.el-scrollbar {
  height: unset;
}
</style>
